package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @program: mytanhua
 * @author: Leon
 * @date: 2021-02-23 16:18
 **/
@Service
@SuppressWarnings("all")
public class IdService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     *  生成自增长的Id,使用Redis实现自增长Id
     * @param type
     * @param strId
     * @return
     */
    public Long createId(String type, String strId) {
//        调用工具类转成大写
        type = StringUtils.upperCase(type);

        String idHashKey = "TANHUA_ID_HASH_" + type;

        if (this.redisTemplate.opsForHash().hasKey(idHashKey, strId)) {
            return Long.valueOf(this.redisTemplate.opsForHash().get(idHashKey, strId).toString());
        }

        String idKey = "TANHUA_ID_" + type;
        Long id = this.redisTemplate.opsForValue().increment(idKey);
        this.redisTemplate.opsForHash().put(idHashKey,strId,id.toString());

        return id;

    }
}
